import 'db_manager.dart';

class BaseInfo {
  String id;
  String name;
}

class UserInfo extends BaseInfo {
  //开发者可以按需自行增加字段
  Map<String, dynamic> toMap() {
    return {'userId': id, 'name': name};
  }
}

//用户信息，用户信息需要开发者自行处理（从 APP 服务获取用户信息并保存），此处只做了最简单的处理
class UserInfoDataSource {
  static Map<String, UserInfo> cachedUserMap = new Map(); //保证同一 userId

  static UserInfoCacheListener cacheListener;

  // 用来刷新用户信息，当有用户信息更新的时候
  static void setUserInfo(UserInfo info) {
    if (info == null) {
      return;
    }
    cachedUserMap[info.id] = info;
    DbManager.instance.setUserInfo(info);
  }

  // 获取用户信息
  static Future<UserInfo> getUserInfo(String userId) async {
    UserInfo cachedUserInfo = cachedUserMap[userId];
    if (cachedUserInfo != null) {
      return cachedUserInfo;
    } else {
      UserInfo info;
      List<UserInfo> infoList =
          await DbManager.instance.getUserInfo(userId: userId);
      if (infoList != null && infoList.length > 0) {
        info = infoList[0];
      }
      if (info == null) {
        if (cacheListener != null) {
          info = cacheListener.getUserInfo(userId);
        }
        if (info != null) {
          DbManager.instance.setUserInfo(info);
        }
      }
      if (info != null) {
        cachedUserMap[info.id] = info;
      }

      if (info == null) {
        info = UserInfo();
      }
      return info;
    }
  }

  static void setCacheListener(UserInfoCacheListener listener) {
    cacheListener = listener;
  }
}

class UserInfoCacheListener {
  UserInfo Function(String userId) getUserInfo;

  void Function(UserInfo info) onUserInfoUpdated;
}
